package com.leo.ktvplayer.ui.payment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.leo.ktvplayer.R;
import com.leo.ktvplayer.base.ActBase;
import com.leo.ktvplayer.bluetooth.BleConstant;
import com.leo.ktvplayer.bluetooth.BleData;
import com.leo.ktvplayer.bluetooth.LeProxy;
import com.leo.ktvplayer.bluetooth.bletask.BleEngineFactory;
import com.leo.ktvplayer.bluetooth.bletask.IBleDataEngine;
import com.leo.ktvplayer.domain.req.ReqCheckDiscountCode;
import com.leo.ktvplayer.domain.req.ReqUploadBill;
import com.leo.ktvplayer.domain.resp.RespCheckDiscountCode;
import com.leo.ktvplayer.localcookie.LocalUtils;
import com.leo.ktvplayer.network.http.HTTPTAG;
import com.leo.ktvplayer.pay.alipay.Alipayment;
import com.leo.ktvplayer.pay.wechat.WechatPayment;
import com.leo.ktvplayer.ui.playing.ActPlaying;
import com.leo.ktvplayer.ui.playing.TimeCounter;
import com.leo.ktvplayer.util.ByteUtils;
import com.leo.ktvplayer.util.JsonUtil;
import com.leo.ktvplayer.util.QRCodeUtil;

import com.leo.ktvplayer.util.TimeFormatUtil;
import com.leo.ktvplayer.util.ToastUtil;

import java.net.Socket;
import java.security.Provider;
import java.text.SimpleDateFormat;
import java.util.jar.JarFile;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Retrofit;
import retrofit2.http.HTTP;

/**
 *
 */
public class ActPayment extends ActBase{

    private Alipayment alipayment;
    private WechatPayment wechatPayment;
    private int time;
    private TimeCounter counter;
    private long orderId;
    private double money;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);
        ButterKnife.bind(this);
        orderId = System.currentTimeMillis();
        time = getIntent().getIntExtra("time",-1);
        money = getIntent().getDoubleExtra("price",-1.0);



        getAlipayCode();
        getWechatCode();
        startCounter();
        startMoneyReceiver();
    }

    private void startMoneyReceiver(){
        IBleDataEngine engine = BleEngineFactory.getInstance(BleConstant.KEY_FOR_OPEN_MONEY_RECEIVER);
        engine.excuteData();
    }

    private void stopMoneyReceiver(){
        IBleDataEngine engine = BleEngineFactory.getInstance(BleConstant.KEY_FOR_CLOSE_MONEY_RECEIVER);
        engine.excuteData();
    }

    private void startCounter(){
        counter = new TimeCounter(1000,3 * 1000 * 60);
        counter.setOnTimeFinishCallback(() -> {
            wechatPayment.tryStopThread();
            alipayment.tryStopThread();

            finish();
            ToastUtil.show("支付超时");
        });
        counter.setOnTimerTickCallBack((currentTime) ->{
            tv_paymentCounterTime.setText("支付倒计时:" + TimeFormatUtil.formatMinAndSecend(currentTime));
        } );
        counter.start();
    }

    private void getWechatCode(){
        wechatPayment = new WechatPayment();
        wechatPayment.setOrderId(orderId + "");
        wechatPayment.setMoney(money);
        wechatPayment.setOnPaymentSuccess(()-> {
            stopAll();
            ToastUtil.show("支付成功");
            goToPlaying();

        });
        wechatPayment.setOnPaymentUrlCallBack((url -> {
            Bitmap bitmap = QRCodeUtil.generateBitmap(url,300,300);
            iv_wechatCode.setImageBitmap(bitmap);
        }));
        wechatPayment.start();
    }

    private void getAlipayCode(){
        alipayment = new Alipayment();
        alipayment.setMoney(money);
        alipayment.setOrderId(orderId + "");
        alipayment.setOnPaymentUrlCallBack((url -> {
            Bitmap logo = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_alipay_logo);
            Bitmap bitmap = QRCodeUtil.createImage(url,300,300,logo);
            iv_alipayCode.setImageBitmap(bitmap);
        }));
        alipayment.setOnPaymentSuccess(() -> {
            stopAll();
            ToastUtil.show("支付成功");

            goToPlaying();


        });
        alipayment.start();
    }



    @OnClick(R.id.btn_discount_code_confirm)
    public void onClick(View view){
        String code = ed_input_discount_code.getText().toString();
        if (TextUtils.isEmpty(code)){
            ToastUtil.show("请输入优惠码");
            return;
        }



    }



    @Override
    protected void httpCall(String json, String tag) {
        super.httpCall(json, tag);
        Log.d("Payfuck","" + tag.equals(HTTPTAG.TAG_FOR_CHECK_DISCOUNT_CODE) + "," + tag);
        if (tag.equals(HTTPTAG.TAG_FOR_CHECK_DISCOUNT_CODE)) {
            RespCheckDiscountCode checkDiscountCode = JsonUtil.jsonStrToObj(RespCheckDiscountCode.class,json);
            if (checkDiscountCode.getCode().equals("200")) {
                goToPlaying();
            } else {
                ToastUtil.show(checkDiscountCode.getMsg());
            }
        } else if (tag.equals(HTTPTAG.TAG_FOR_UPLOADBILL)) {
            //TODO do something

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(moneyReceiver, new IntentFilter(LeProxy.ACTION_DATA_AVAILABLE));
    }

    @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(moneyReceiver);
    }

    private void stopAll(){
        alipayment.tryStopThread();
        wechatPayment.tryStopThread();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        counter.cancel();//停止计时器
        stopMoneyReceiver();
    }

    private void goToPlaying(){
        Intent intent = new Intent(this, ActPlaying.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(ActPlaying.TAG_PLAY_TIME,time);
        startActivity(intent);
        finish();
        IBleDataEngine engine = BleEngineFactory.getInstance(BleConstant.KEY_FOR_LOCK_DEVICE);
        engine.excuteData();//发送指令 开锁
    }

    private BroadcastReceiver moneyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] data = intent.getByteArrayExtra(LeProxy.EXTRA_DATA);
            Log.d("acthome", ByteUtils.byte2String(data));
            if (data[2] == 0x02){//收钱器
                IBleDataEngine bleDataEngine = BleEngineFactory.getInstance(BleConstant.KEY_FOR_READ_MONEY);
                carsh +=bleDataEngine.receiveMoney(data[3]);
                tv_cashReceiver.setText(carsh + "元");
                if (carsh >= money){
                    goToPlaying();
                }
            } else if (data[2] == 0x01){
                carsh +=1;
                tv_cashReceiver.setText(carsh + "元");
                if (carsh >= money){
                    goToPlaying();
                }
            }

        }
    };




    @BindView(R.id.iv_wechatqrcode)
    public ImageView iv_wechatCode;
    @BindView(R.id.iv_alipayqrcode)
    public ImageView iv_alipayCode;

    @BindView(R.id.ed_input_discouent_code)
    public EditText ed_input_discount_code;
    @BindView(R.id.btn_discount_code_confirm)
    public Button btn_confirm_discount_code;

    @BindView(R.id.tv_payment_countertime)
    public TextView tv_paymentCounterTime;

    @BindView(R.id.tv_activity_payment_cash)
    public TextView tv_cashReceiver;

    private int carsh;

    private static final String PAY_TYPE_ALIPAY = "支付宝";
    private static final String PAY_TYPE_WECHAT = "微信支付";
    private static final String PAY_TYPE_CASH = "现金";
}
